#include "ButtonAndBattery.h"
#include "BuzzerSound.h"
#include "OneButton.h"
#include "RGBLED.h"

OneButton bnt(BUTTON_PIN, true);
uint16_t batteryVoltage;
void balanceCarPowerOn()
{
    digitalWrite(POWEREN_PIN, HIGH);
}

void balanceCarPowerOff()
{
    buzzer.play(powerOffID);
    rgb.TurnOff();
    digitalWrite(POWEREN_PIN, LOW);
}

void turnOffRGB()
{
    buzzer.play(powerOffledID);
    rgb.TurnOff();
}

void focSelfCheckCompleted()
{
    buzzer.play(S_BEEP);
}

// 自检完成函数

void CheckBatteryVoltageForSafety() // 检测电压是否低于7.25V
{
    batteryVoltage = analogRead(BAT_ADC_PIN); //
    if (batteryVoltage < 3000)
    {
        buzzer.play(S_SIREN);
        // digitalWrite(POWEREN_PIN, LOW);
        // Serial.println(batteryVoltage );
    }
}

void ButtonEventTask(void *pvParameters) // 按键检测任务
{

    pinMode(POWEREN_PIN, OUTPUT); // 初始化电源引脚
    balanceCarPowerOn();          // 启动电源

    buzzer.Init(BUZZER_PIN); // 初始化蜂鸣器
    buzzer.play(powerOnID);  // 启动声音

    bnt.reset();                                  // 按键复位
    bnt.attachLongPressStart(balanceCarPowerOff); // 长按电源键关机
    bnt.attachClick(turnOffRGB);                  // 单击电源键切换颜色
    // bnt.attachDoubleClick(turnOffRGB);            // 双击电源键关闭LED

    rgb.Initialize();

    for (;;)
    {
        bnt.tick();
        vTaskDelay(50);
    }
};

void BatteryVoltageCheckTask(void *pvParameters) // 按键和电压检测任务
{
    pinMode(BAT_ADC_PIN, INPUT); // 初始化电池电压检测引脚
    for (;;)
    {
        CheckBatteryVoltageForSafety();
        vTaskDelay(50);
    }
};

void BNT_AND_PWR::startTask()
{

    xTaskCreatePinnedToCore(ButtonEventTask, "Button_Event", 2048, NULL, 2, NULL, 0);
    xTaskCreatePinnedToCore(BatteryVoltageCheckTask, "Battery_Voltage_Check", 2048, NULL, 5, NULL, 1);
};

BNT_AND_PWR ButtonAndPower;
